package com.tiku.filter;



import com.tiku.advice.TokenException;
import com.tiku.entity.LoginUser;
import com.tiku.entity.entityInterface;
import com.tiku.mapper.UserInfoMapper;
import com.tiku.utils.JwtUtil;
import com.tiku.utils.RedisCache;
import com.tiku.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }

        Claims claims = null;
        String userID;
        try {
            //解析token
            claims = JwtUtil.parseJWT(token);
            userID=claims.getSubject();//获取主体内容
        } catch (Exception e) {
            throw new TokenException("非法token！");
        }
        //从redis中查出对应的用户信息
        Object cacheObject = redisCache.getCacheObject("user:"+userID);
        if (Objects.isNull(cacheObject)||!cacheObject.equals(token)){
            throw new TokenException("token失效");
        }

        //TODO 权限问题
        entityInterface entity=null;
        entity = userInfoMapper.selectById(userID);

        LoginUser user=new LoginUser(entity);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        //通知后续过滤器链 此请求已经认证成功
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        ThreadLocalUtil.setThreadLocal(userID);
        filterChain.doFilter(request,response);

    }
}
